package at.bubblebird.todoapp;

import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class TodoActivity extends Activity {
    
	private String sessionID = null;
	private ProgressDialog loader;
    
	private ArrayList<String> todos;
    
    public static TodoActivity instance;
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        instance = this;
        
        setContentView(R.layout.main);
        
        findViewById(R.id.loginButton).setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(findViewById(R.id.loginButton).getWindowToken(), 0);
				try {
					loader = ProgressDialog.show(TodoActivity.this, "", "logging in ...", true, false);
					new LoginAsyncTask().execute(new URL("http://www.bubblebird.at/todo_server/index.php?action=login&name="+((EditText)findViewById(R.id.nickField)).getText()+"&pw="+((EditText)findViewById(R.id.pwField)).getText()));
				} catch (Exception e){
					e.printStackTrace();
				}
			}
        });
    }
    
    public void setSessionID(String sID){
    	sessionID = sID;
    	if(loader != null)loader.dismiss();
    	Toast.makeText(TodoActivity.this, sessionID, Toast.LENGTH_LONG).show();
    	if(sessionID != null) loadTodos();
    }
    
    public void setTodos(ArrayList<String> todos){
    	this.todos = todos;
    	if(loader != null)loader.dismiss();
    	showTodos();
    }
    
    public void loadTodos(){
    	if(loader != null)loader.dismiss();
    	try {
    		loader = ProgressDialog.show(TodoActivity.this, "", "loading todos ...", true, false);
    		new LoadTodosAsyncTask().execute(new URL("http://www.bubblebird.at/todo_server/index.php?action=getTodos&sID="+this.sessionID));
    	} catch (Exception e){
			e.printStackTrace();
		}
    }
    
    public void showTodos(){
    	setContentView(R.layout.todos);
    	((ListView)findViewById(R.id.todoList)).setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, todos));
    }
}